import { Mutation, Action } from 'vuex';
import {
    login,
    getUserInfo
} from '@/api/user';
import { removeToken } from "@/utils/localToken";
import {
    RoutesDataItem
} from '@/routes'
import { setRouter } from '@/utils/AddRouters';
import homeRoter from '@/routes/homeRoutes';


/**
 * 获取当前用户信息
 */
export interface CurrentUser {
    id: number;
    name: string;
    avatar: string;
    roles: string[];
    menus: RoutesDataItem[]; //菜单
    routes: RoutesDataItem[];//路由
    loginStatus?: 'ok' | 'error';
}
 
export interface ModuleType {
    namespaced: true;
    name: string;
    state: CurrentUser;
    getters: {
        getMenus: Mutation<CurrentUser>;
        getRoutes: Mutation<CurrentUser>;
        getLoginStatus: Mutation<CurrentUser>;
    };
    mutations: {
        saveCurrentUser: Mutation<CurrentUser>;
        setMenus: Mutation<CurrentUser>;
        setRouters: Mutation<CurrentUser>;
        changeLoginStatus: Mutation<CurrentUser>;
    };
    actions: {
        login: Action<CurrentUser, CurrentUser>;
        getUserInfo: Action<CurrentUser, CurrentUser>;
        logout: Action<CurrentUser, CurrentUser>;
    };
}

const initState: CurrentUser = {
    id: 0,
    name: '',
    avatar: '',
    roles: [],
    menus: [],
    routes: [],
    loginStatus: 'error'
}

const StoreModel: ModuleType = {
    namespaced: true,
    name: 'user',
    state: {
        ...initState
    },
    getters: {
        getMenus: (state) => {
            return state.menus;
        },
        getRoutes: (state) => {
            return state.routes;
        },
        getLoginStatus: (state) => {
            return state.loginStatus;
        }
    },
    mutations: {
        changeLoginStatus(state, payload) {
            state.loginStatus = payload;
        },
        saveCurrentUser(state, payload) {
            state = {
                ...initState,
                ...payload,
            }
        },
        setMenus: (state, payload) => {
            state.menus = payload;
        },
        setRouters: (state, routers) => {
            state.routes = routers;
        },
    },
    actions: {
        async login({ commit }, payload) {
            let state = undefined;
            try {
                const res = await login(payload)
                // console.log(JSON.stringify(res))
                state = 'ok'
            } catch (error) {
                if (error.message && error.message === 'CustomError') {
                    state = 'error';
                }
            }
            commit("changeLoginStatus", state);

            if (state === 'ok') {
                return true;
            } else {
                return false;
            }
        },
        async getUserInfo({ commit },payload) {
            try {
                const response = await getUserInfo();
                // console.log(JSON.stringify(response))
                const { data, menus } = response.data;
                commit('saveCurrentUser', data || {});
                commit("setMenus", [...homeRoter, ...menus] || []);
                const routers = setRouter(menus || []); 
                commit("setRouters", routers);
                return routers;
            } catch (error) {
                return false;
            }
        },
        async logout({ commit }) {
            try {
                await removeToken();
                commit('saveCurrentUser', { ...initState });
                return true;
            } catch (error) {
                return false;
            }
        }
    }
}


export default StoreModel;
